﻿using FarmSmartSleep.Common.Domain;
using FarmSmartSleep.Common.Domain.BeginTable;
using FarmSmartSleep.Common.Domain.PM;
using FarmSmartSleep.Common.Domain.PM.select;
using FarmSmartSleep.Common.Domain.RBACFile;
using FarmSmartSleep.Common.Dtos;
using FarmSmartSleep.Common.Infrastructure;
using MediatR;

namespace FarmSmartSleep.Organ.API.Application.ProductionManagement.MotherHybridizationCommands
{
    public class MotherHybridizationSearchHander : IRequestHandler<MotherHybridizationSearchCommand, ResultPage<MotherHybirdizationSearchDto>>
    {

        private readonly IBaseRepository<MotherHybridization> motherRepository;
        private readonly IBaseRepository<SleepInfor> sleepRepository;
        private readonly IBaseRepository<HybridizationType> hybridizationTypeRepository;
        private readonly IBaseRepository<EstrusType> estrusTypeRepository;
        private readonly IBaseRepository<Employee> employeeRepository;
        private readonly IBaseRepository<Variety> varietyRepository;
        private readonly IBaseRepository<Cottages>cottageTypeRepository;
        private readonly IBaseRepository<Fields> fildsTypeRepository;
        private readonly ILogger<MotherHybridizationSearchHander> logger;

        public MotherHybridizationSearchHander(IBaseRepository<MotherHybridization> motherRepository, IBaseRepository<SleepInfor> sleepRepository, IBaseRepository<HybridizationType> hybridizationTypeRepository, IBaseRepository<EstrusType> estrusTypeRepository, IBaseRepository<Employee> employeeRepository, IBaseRepository<Variety> varietyRepository, IBaseRepository<Cottages> cottageTypeRepository, IBaseRepository<Fields> fildsTypeRepository, ILogger<MotherHybridizationSearchHander> logger)
        {
            this.motherRepository = motherRepository;
            this.sleepRepository = sleepRepository;
            this.hybridizationTypeRepository = hybridizationTypeRepository;
            this.estrusTypeRepository = estrusTypeRepository;
            this.employeeRepository = employeeRepository;
            this.varietyRepository = varietyRepository;
            this.cottageTypeRepository = cottageTypeRepository;
            this.fildsTypeRepository = fildsTypeRepository;
            this.logger = logger;
        }

        /// <summary>
        /// 分页查询种母配种信息
        /// </summary>
        /// <param name="request">分页查询种母配种信息请求对象</param>
        /// <param name="cancellationToken"></param>
        /// <returns>分页查询种母配种信息响应对象</returns>
        public async Task<ResultPage<MotherHybirdizationSearchDto>> Handle(MotherHybridizationSearchCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result = new ResultPage<MotherHybirdizationSearchDto>();
                var list = (from a in motherRepository.GetAll().Where(c=>!c.Deletes)
                           join b in sleepRepository.GetAll() on a.MotherHybridizationId equals b.SleepInforId
                           join c in sleepRepository.GetAll() on a.FatherSleepInforId equals c.SleepInforId
                           join d in hybridizationTypeRepository.GetAll() on a.HybridizationTypeId equals d.HybridizationTypeId
                           join e in estrusTypeRepository.GetAll() on a.EstrusTypeId equals e.EstrusTypeId
                           join f in cottageTypeRepository.GetAll() on a.ToCottageId equals f.CottagesId
                           join g in fildsTypeRepository.GetAll() on a.ToFieIdId equals g.FieIdId
                           join h in employeeRepository.GetAll() on a.ChargePerson equals h.EmployeeId
                           join i in employeeRepository.GetAll() on a.CreateId equals i.EmployeeId
                           join j in varietyRepository.GetAll() on b.VarietyId equals j.VarietyId
                           join k in varietyRepository.GetAll() on c.VarietyId equals k.VarietyId
                           join l in cottageTypeRepository.GetAll() on b.RecordcottageId equals l.CottagesId
                           join m in fildsTypeRepository.GetAll() on c.FieIdId equals m.FieIdId
                            select new MotherHybirdizationSearchDto
                           {
                               MotherHybridizationId = a.MotherHybridizationId,
                               MotherSleepInforId = a.MotherSleepInforId,
                               MotherEarNumber = b.EarNumber,
                               FatherSleepInforId = a.FatherSleepInforId,
                               FatherEarNumber = c.EarNumber,
                               EstrusTypeId = a.EstrusTypeId,
                               EstrusTypeName = e.EstrusTypeName,
                               HybridizationTypeId  = a.HybridizationTypeId,
                               HybridizationTypeName = d.HybridizationTypeName,
                               Mark = a.Mark,
                               ToCottageId = a.ToCottageId,
                               ToCottageName = f.CottageName,
                               ToFieIdId = a.ToFieIdId,
                               ToFieIdName = g.FieIdName,
                               DocumentNumber = a.DocumentNumber,
                               ChargePerson = a.ChargePerson,
                               ChargePersonName = h.FirstName,
                               CreateId = a.CreateId,
                               CreateTime = a.CreateTime,
                               CreateName = i.FirstName,
                               UpdateId = a.UpdateId,
                               UpdateTime = a.UpdateTime,
                               ExamId = a.ExamId,
                               ExamTime = a.ExamTime,
                               MotherTypeName = j.VarietyName,
                               FatherTypeName = k.VarietyName,
                               NowCottageName = l.CottageName,
                               NowFiedName = m.FieIdName,
                               BreedStatuId = b.BreedStatuId
                           }).ToList();

                foreach (var item in list)
                {
                    if (item.UpdateId > 0)
                    {
                        item.UpdateName = employeeRepository.GetAll().FirstOrDefault(c => c.EmployeeId == item.UpdateId).FirstName;
                    }
                    if (item.ExamId > 0)
                    {
                        item.ExamName = employeeRepository.GetAll().FirstOrDefault(c => c.EmployeeId == item.ExamId).FirstName;
                    }
                }

                if(!string.IsNullOrEmpty(request.StartDate))
                {
                    list = list.Where(c => c.CreateTime >= Convert.ToDateTime(request.StartDate)).ToList();
                }
                if (!string.IsNullOrEmpty(request.EndDate))
                {
                    list = list.Where(c => c.CreateTime <= Convert.ToDateTime(request.EndDate)).ToList();
                }
                if (!string.IsNullOrEmpty(request.MotherEarNumber))
                {
                    list = list.Where(c => c.MotherEarNumber.Contains(request.MotherEarNumber)).ToList();
                }
                if (request.ChargePerson!=0)
                {
                    list = list.Where(c => c.ChargePerson==request.ChargePerson).ToList();
                }

                if (request.PageIndex != 0)
                {
                    result.totalCount = list.Count();
                    result.totalPage = (int)Math.Ceiling((result.totalCount) * 1.0 / request.PageSize);
                    result.Data = list.OrderBy(c => c.MotherHybridizationId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
                }
                else
                {
                    result.Data = list;
                }
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError("获取配种信息列表方法调用出错" + ex);
                throw;
            }
        }
    }
}
